package com.voicechat.firstmet.utils;

import com.voicechat.firstmet.realm.ListBean;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmResults;

/**
 * author: tao yong<br/>
 * time: 2017/10/31 19:35<br/>
 * introduce: <br/>
 */

public class RealmUtils {
    private static final String TAG = "RealmUtils";
    private static RealmUtils sInstance;
    private Realm realm;

    private RealmUtils() {
        realm = Realm.getDefaultInstance();
    }

    public static RealmUtils getInstance() {
        if (null == sInstance) {
            synchronized (RealmUtils.class) {
                if (null == sInstance) {
                    sInstance = new RealmUtils();
                }
            }
        }
        return sInstance;
    }

    public <T extends RealmObject> void copyToRealmOrUpdate(T t) {
        try {
            realm.beginTransaction();
            realm.copyToRealmOrUpdate(t);
            realm.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public <T extends RealmObject> void deleteToRealm(int i) {
        try {
            RealmResults<ListBean> results = RealmUtils.getInstance()
                    .getRealm()
                    .where(ListBean.class)
                    .findAll();
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    results.deleteFromRealm(i);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public <T extends RealmObject> List<T> queryAll(Class<T> cls) {
        RealmResults<T> results = null;
        try {
            results = realm.where(cls).findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }

    public Realm getRealm() {
        return realm;
    }

    public void beginTransaction() {
        realm.beginTransaction();
    }

    public void commitTransaction() {
        realm.commitTransaction();
    }
}